package com.atguigu.jinx.service.impl;

import com.atguigu.jinx.entity.dto.User;
import com.atguigu.jinx.entity.vo.*;
import org.apache.commons.io.FilenameUtils;
import com.atguigu.jinx.exception.BusinessException;
import com.atguigu.jinx.mapper.UserMapper;
import com.atguigu.jinx.service.IUserService;
import com.atguigu.jinx.utils.transfer.CommonMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.atguigu.jinx.utils.NameConstants.USER_PICTURE_FILETYPE_ERROR;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author steve
 * @since 2025-08-07
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    @Value("${maxCount}")
    private int maxCount;


    /**
     * 上传图片所允许的文件格式
     */
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(
            "jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff", "svg"
    );

    private final TencentCosService tencentCosService;

    @Override
    public NicknameAndPictureVO getNicknameAndPicture() {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, SecurityContextHolder.getContext().getAuthentication().getName()));
        NicknameAndPictureVO vo = new NicknameAndPictureVO();
        vo.setNickname(user.getNickName());
        vo.setIconUrl(user.getIconUrl());
        vo.setMember(user.getIsMember());
        return vo;
    }


    @Override
    public boolean suggestion(SuggestionVO suggestionVO) {
        String usrSuggestion = suggestionVO.getUsrSuggestion();
        String contactWay = suggestionVO.getContactWay();
        Integer num = userMapper.selectSuggestion(contactWay);

        // 超过最大值不允许评论
        if (num > maxCount) {
            return false;
        }
        int result = userMapper.insertSuggestion(usrSuggestion, contactWay);
        return result == 1;
    }


    @Override
    public UserDisplayInfoVO displayPersonalInfo() {
        Long userId = getUserId();
        User user = userMapper.selectById(userId);
        Assert.notNull(user, "未找到该用户的相关信息");
        UserDisplayInfoVO userDisplayInfoVO = CommonMapper.INSTANCE.userToDisplayInfo(user);
        return userDisplayInfoVO;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean changePersonalInfo(ChangePersonalVO changePersonalVO) {
        Long userId = getUserId();
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (StringUtils.isNotBlank(changePersonalVO.getNickName())) {
            user.setNickName(changePersonalVO.getNickName());
        }
        if (StringUtils.isNotBlank(changePersonalVO.getIconUrl())) {
            user.setIconUrl(changePersonalVO.getIconUrl());
        }
        if (StringUtils.isNotBlank(changePersonalVO.getPhone())) {
            user.setPhone(changePersonalVO.getPhone());
        }
        if (StringUtils.isNotBlank(changePersonalVO.getEmail())) {
            user.setEmail(changePersonalVO.getEmail());
        }
        if (StringUtils.isNotBlank(changePersonalVO.getWechatNum())) {
            user.setWechatNum(changePersonalVO.getWechatNum());
        }
        return updateById(user);
    }

    /**
     * 图片上传到云存储,并且可以进行图片的展示
     *
     * @param file 图片
     * @return 图片的Url
     */
    @Override
    public String uploadPicToStorage(MultipartFile file) throws IOException {
        // 图片格式检查
        if (!checkFileType(file)){
            return USER_PICTURE_FILETYPE_ERROR;
        }
        // 构造文件名称
        String fileName = "images/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

        // 上传到 COS
        return tencentCosService.uploadMultipartFile(file, fileName);
    }


    private boolean checkFileType(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return false;
        }
        String extension = FilenameUtils.getExtension(originalFilename).toLowerCase();
        return ALLOWED_EXTENSIONS.contains(extension);

    }


    private Long getUserId() {
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userName));
        Assert.notNull(user, "未找到该用户");
        return user.getId();
    }
}
